package com.mjf.kxml.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mjf.common.utils.DateUtils;
import com.mjf.kxml.domain.Merchant;
import com.mjf.kxml.enums.CKApiEnum;
import com.mjf.kxml.enums.SendFlagEnum;
import com.mjf.kxml.mapper.MerchantMapper;
import com.mjf.kxml.service.MerchantService;
import com.mjf.kxml.util.CKHttpSendUtil;
import com.mjf.kxml.util.CKResultVO;
import com.mjf.kxml.vo.MerchantLogQuery;
import com.mjf.kxml.vo.MerchantLogResVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * desc
 * </p>
 *
 * @author chenshoumeng
 * @date 2025/6/4 13:31
 */
@Service
@Slf4j
public class MerchantServiceImpl extends ServiceImpl<MerchantMapper, Merchant> implements MerchantService {

    @Override
    public CKResultVO sendAll() {
        log.info("开始推送客商数据");
        // 查询未发送的数据
        List<Merchant> merchantLists = list(Wrappers.<Merchant>lambdaQuery().ne(Merchant::getPullsk,
            SendFlagEnum.SEND_FLAG_YES.getCodes()));

        if (CollectionUtil.isNotEmpty(merchantLists)) {
            for (Merchant m : merchantLists) {
                List<Merchant> merchantList = Collections.singletonList(m);
                merchantList.forEach(merchant -> {
                    merchant.setPulltime(LocalDateTime.now());
                });
                try {
                    String soapXml = Merchant.buildObjectXml(IdUtil.fastSimpleUUID(), merchantList);
                    CKResultVO ckResultVO = CKHttpSendUtil.sendXml(CKApiEnum.CK_API_CONTRACT, soapXml);
                    String sk = "";
                    if (ckResultVO.getSuccess()) {
                        sk = SendFlagEnum.SEND_FLAG_YES.getCodes();
                    } else {
                        log.error("发送客商数据失败 {}", ckResultVO);
                        sk = SendFlagEnum.SEND_FLAG_FAIL.getCodes();
                    }
                    String finalSk = sk;
                    merchantList.forEach(merchant -> {
                        merchant.setPullsk(finalSk);
                        merchant.setPullskoutstr(ckResultVO.getData());
                    });
                    updateBatchById(merchantList);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("发送客商数据异常 ", e);
                    merchantList.forEach(merchant -> {
                        merchant.setPullsk(SendFlagEnum.SEND_FLAG_FAIL.getCodes());
                        merchant.setPullskoutstr(e.getMessage());
                    });
                    updateBatchById(merchantList);
                }
            }
        }
        log.info("客商推送完成");
        return CKResultVO.buildSuccess("N", "发送失败", "");
    }

    @Override
    public IPage<MerchantLogResVO> merchantLogs(MerchantLogQuery query) {
        IPage<MerchantLogResVO> res = new Page<>();
        res.setRecords(new ArrayList<>());
        res.setPages(query.getPage());
        res.setSize(query.getSize());
        LambdaQueryWrapper<Merchant> qw = new LambdaQueryWrapper<>();
        qw.eq(StrUtil.isNotBlank(query.getPullsk()), Merchant::getPullsk, query.getPullsk());
        qw.ge(StrUtil.isNotBlank(query.getStart()), Merchant::getPulltime, query.getStart());
        qw.le(StrUtil.isNotBlank(query.getEnd()), Merchant::getPulltime, query.getEnd());
        int count = count(qw);
        res.setTotal(count);
        if (count < 1) {
            return res;
        }
        qw.last(" limit " + (query.getPage() - 1) * query.getSize() + "," + query.getSize());
        List<Merchant> list = list(qw);
        res.setRecords(list.stream().map(e -> MerchantLogResVO.builder()
            .id(e.getId())
            .ccarGsname(e.getCcarGsname())
            .ccarGscode(e.getCcarGscode())
            .number(e.getNumber())
            .name(e.getName())
            .ccarVendorname(e.getCcarVendorname())
            .ccarLegalperson(e.getCcarLegalperson())
            .ccarVendorcode(e.getCcarVendorcode())
            .ccarRegcapital(e.getCcarRegcapital())
            .ccarSetdate(e.getCcarSetdate())
            .ccarVendoraddress(e.getCcarVendoraddress())
            .ccarCountry(e.getCcarCountry())
            .ccarSubcompany(e.getCcarSubcompany())
            .ccarVendortype(e.getCcarVendortype())
            .ccarVendorcategory(e.getCcarVendorcategory())
            .ccarDayidx(e.getCcarDayidx())
            .ccarStandby1(e.getCcarStandby1())
            .ccarStandby2(e.getCcarStandby2())
            .ccarStandby3(e.getCcarStandby3())
            .ccarStandby4(e.getCcarStandby4())
            .ccarStandby5(e.getCcarStandby5())
            .ccarStandby6(e.getCcarStandby6())
            .ccarStandby7(e.getCcarStandby7())
            .ccarStandby8(e.getCcarStandby8())
            .ccarStandby9(e.getCcarStandby9())
            .ccarStandby10(e.getCcarStandby10())
            .times(DateUtils.toLocalDateTimeString(e.getTimes()))
            .pullsk(e.getPullsk())
            .pullskoutstr(e.getPullskoutstr())
            .pulltime(DateUtils.toLocalDateTimeString(e.getPulltime()))
            .build()).collect(Collectors.toList()));
        return res;
    }
}
